package com.jt.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLibProxy {
    public static Object getProxy(Object target) {
        //创建增强对象
        Enhancer enhancer = new Enhancer();
        //设定父级 目标对象
        enhancer.setSuperclass(target.getClass());
        //定义回调方法,代理对象执行目标方法是调用
        enhancer.setCallback(getMethodIInterceptor(target));
        //创建代理对象
        return enhancer.create();
    }

    public static MethodInterceptor getMethodIInterceptor(Object target) {

        return new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("事物开始");
                Object result = method.invoke(target, objects);
                System.out.println("事务提交");
                return result;
            }
        };
    }
}
